import Vue from "vue";
import Router from "vue-router";
import store from "../store/index";
// import { Toast } from 'vant';
Vue.use(Router);

const router = new Router({
    mode: 'history',
    routes: [{
        path: "/",
        redirect: "/index"
    },
    // 登录
    {
        path: "/login",
        name: 'login',
        component: () =>
            import("@/views/login/index"),
        meta: {
            title: "登陆"
        }
    },
    // 首页
    {
        path: "/index",
        name: 'index',
        component: () =>
            import("@/views/index/index"),
        meta: {
            title: "诚德科技",
            // 缓存首页
            needLogin: true
        }
    },
    // 404
    {
        path: "*",
        component: () =>
            import("@/components/NotFound")
    },
    ]
});

// 路由门卫
router.beforeEach((to, from, next) => {
    let { title, needLogin } = to.meta;// 页面标题
    if (to.name == 'login') {// 过期退出清缓存
        $cookies.remove('totalInfo')
        store.commit('updateToken', null)
        next()
        return
    }
    document.title = title;

    if (needLogin && (!$cookies.get('totalInfo') || !store.state.token)) {
        console.log("用户不存在，请重新登录");
        // Toast.fail('用户不存在，请重新登录');
        // 清空token
        store.commit('updateToken', null);
        next({
            path: "/login"
        });
    } else {
        console.log("进行跳转");
        next();
    }
});

export default router;